package com.ruoyi.plus.pub.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.plus.constants.PlusDictConstants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.plus.pub.api.vo.PubNoticePlusVo;
import com.ruoyi.plus.pub.controller.po.PubNoticeReceiversPo;
import com.ruoyi.plus.pub.service.IPubNoticePlusService;
import com.ruoyi.plus.pub.domain.PubNoticePlus;
import com.ruoyi.plus.pub.domain.PubNoticeReceiver;
import com.ruoyi.plus.pub.service.IPubNoticeReceiverService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 系统公告通知Controller
 *
 */
@RestController
@RequestMapping("/pub/noticePlus")
public class PubNoticePlusController extends BaseController {
    @Autowired
    private IPubNoticePlusService pubNoticePlusService;
    @Autowired
    private IPubNoticeReceiverService pubNoticeReceiverService;

    private static void ListSort(List<PubNoticePlus> list) {
        //定义一个比较器
        list.sort((o1, o2) -> {
            try {
                Date dt1 = o1.getNoticeStartTime();
                Date dt2 = o2.getNoticeStartTime();
                if (dt1 != null && dt2 != null) {
                    return dt1.compareTo(dt2);
                }
                return 0;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 0;
        });
    }

    /**
     * 查询系统公告通知列表
     */
    @PreAuthorize("@ss.hasPermi('pub:noticePlus:list')")
    @GetMapping("/list")
    public TableDataInfo list(PubNoticePlus pubNoticePlus) {
        startPage();
        List<PubNoticePlus> list = pubNoticePlusService.selectPubNoticePlusList(pubNoticePlus);
        return getDataTable(list);
    }

    /**
     * 导出系统公告通知列表
     */
    @PreAuthorize("@ss.hasPermi('pub:noticePlus:export')")
    @Log(title = "系统公告通知导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(PubNoticePlus pubNoticePlus) {
        List<PubNoticePlus> list = pubNoticePlusService.selectPubNoticePlusList(pubNoticePlus);
        ExcelUtil<PubNoticePlus> util = new ExcelUtil<>(PubNoticePlus.class);
        return util.exportExcel(list, "noticePlus");
    }

    /**
     * 获取系统公告通知详细信息
     */
    @PreAuthorize("@ss.hasAnyPermi('pub:noticePlus:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(pubNoticePlusService.getById(id));
    }

    /**
     * 新增保存系统公告通知
     */
    @PreAuthorize("@ss.hasPermi('pub:noticePlus:add')")
    @Log(title = "系统公告通知添加", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PubNoticePlus pubNoticePlus) {
        Calendar now = Calendar.getInstance();
        pubNoticePlus.setNoticeStartTime(now.getTime());
        now.add(Calendar.YEAR, 1);
        pubNoticePlus.setNoticeEndTime(now.getTime());
        return toAjax(pubNoticePlusService.save(pubNoticePlus));
    }

    /**
     * 修改保存系统公告通知
     */
    @PreAuthorize("@ss.hasPermi('pub:noticePlus:edit')")
    @Log(title = "系统公告通知修改", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody PubNoticePlus pubNoticePlus) {
        return toAjax(pubNoticePlusService.updatePubNoticePlus(pubNoticePlus));
    }

    /**
     * 删除系统公告通知
     */
    @PreAuthorize("@ss.hasPermi('pub:noticePlus:remove')")
    @Log(title = "系统公告通知删除", businessType = BusinessType.DELETE)
    @PostMapping("/del/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        List<Long> list = Arrays.asList(ids);
        return toAjax(pubNoticePlusService.removeNotice(list));
    }

    /**
     * 跳转用户列表页
     *
     * @param noticeId
     * @return
     */
    @GetMapping("/toUsers/{noticeId}")
    public AjaxResult toUsers(@PathVariable Long noticeId) {
        return AjaxResult.success(pubNoticeReceiverService.noticeReceiverIds(noticeId));
    }

    /**
     * 保存通知接收人信息
     *
     * @param pubNoticeReceiversPo
     * @return
     */
    @PreAuthorize("@ss.hasPermi('pub:noticePlus:receiver')")
    @Log(title = "通知接收人", businessType = BusinessType.INSERT)
    @PostMapping("/saveReceivers")
    @ResponseBody
    public AjaxResult saveReceivers(@RequestBody PubNoticeReceiversPo pubNoticeReceiversPo) {
        PubNoticePlus pubNoticePlus = pubNoticePlusService.getById(pubNoticeReceiversPo.getNoticeId());
        pubNoticeReceiverService.deleteAndSaveReceivers(pubNoticeReceiversPo.getUserIds(), pubNoticePlus);
        return AjaxResult.success();
    }

    /**
     * 获取用户未读通知数
     *
     * @return
     */
    @GetMapping("/count")
    public AjaxResult unReadNoticeCount() {
        return AjaxResult.success(pubNoticeReceiverService.unReadCount(SecurityUtils.getLoginUser().getUserId(),null));
    }

    /**
     * 查询系统公告通知列表
     */
    @GetMapping("/myList")
    public AjaxResult myList(PubNoticePlus pubNoticePlus) {
        if (PlusDictConstants.NOTICE_PLUS_TYPE_PUBLIC.equals(pubNoticePlus.getType())) {
            //获取公告
            pubNoticePlus.setType(PlusDictConstants.NOTICE_PLUS_TYPE_PUBLIC);
            pubNoticePlus.setStatus(PlusDictConstants.NOTICE_PLUS_STATUS_RELEASE);
            List<PubNoticePlus> list = pubNoticePlusService.selectPubNoticePlusList(pubNoticePlus);
            return AjaxResult.success(list);
        }
        pubNoticePlus.setUserId(SecurityUtils.getLoginUser().getUserId());
        List<PubNoticePlus> list1 = pubNoticePlusService.myNotices(pubNoticePlus);
        //获取公告
        pubNoticePlus.setType(PlusDictConstants.NOTICE_PLUS_TYPE_PUBLIC);
        pubNoticePlus.setStatus(PlusDictConstants.NOTICE_PLUS_STATUS_RELEASE);
        List<PubNoticePlus> list = pubNoticePlusService.selectPubNoticePlusList(pubNoticePlus);
        list1.addAll(list);
        ListSort(list1);
        return AjaxResult.success(list1);
    }

    /**
     * 获取系统公告通知对象
     */
    @GetMapping(value = "/getNotice/{noticeId}")
    @ResponseBody
    public AjaxResult getNotice(@PathVariable("noticeId") Long noticeId) {
        PubNoticePlus entity = pubNoticePlusService.getById(noticeId);

        //如果是通知并且userId不为空,修改阅读状态
        PubNoticeReceiver pubNoticeReceiver = new PubNoticeReceiver();
        pubNoticeReceiver.setNoticeId(entity.getId());
        pubNoticeReceiver.setUserId(SecurityUtils.getLoginUser().getUserId());
        pubNoticeReceiver.setReadStatus(PlusDictConstants.NOTICE_PLUS_READ_STATUS_READ);
        pubNoticeReceiverService.updateReadStatus(pubNoticeReceiver);
        entity.setReadStatus(PlusDictConstants.NOTICE_PLUS_READ_STATUS_READ);
        PubNoticePlusVo vo = new PubNoticePlusVo();
        BeanUtils.copyProperties(entity, vo);
        return AjaxResult.success(vo);
    }
}
